package cn.glutnn.service.impl;

import cn.glutnn.entity.Result;
import cn.glutnn.entity.User;
import cn.glutnn.entity.dto.MessageDTO;
import cn.glutnn.handler.ChatWebSocketHandler;
import cn.glutnn.mapper.MessagesMapper;
import cn.glutnn.service.MessagesService;
import cn.glutnn.service.UserService;
import cn.glutnn.utils.ThreadLocalUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
import cn.glutnn.entity.Messages;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (Messages)表服务实现类
 *
 * @author msh
 * @since 2024-12-27 13:06:42
 */
@Service("messagesService")
public class MessagesServiceImpl extends ServiceImpl<MessagesMapper, Messages> implements MessagesService {
    @Autowired
    private ChatWebSocketHandler chatWebSocketHandler;
    @Resource
    private UserService userService;

    @Override
    public void sendMessage(Messages messages) throws IOException {
        // 1. 保存消息到数据库
        save(messages);
        chatWebSocketHandler.sendMessage(messages.getReceiverId(), messages.getMessage());
    }


    // 接收所有消息
    @Override
    public Result<List<MessageDTO>> getMessages(int userId) {
        LambdaQueryWrapper<Messages> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Messages::getReceiverId, userId)
                .or()
                .eq(Messages::getSenderId, userId)
                .orderByDesc(Messages::getCreatedTime);
        List<Messages> messages = list(wrapper);
        ArrayList<MessageDTO> messageDTOS = new ArrayList<>();
        messages.forEach(message -> {
            Integer id;
            if (message.getSenderId() != userId) {
                id = message.getSenderId();
            } else {
                id = message.getReceiverId();
            }
            User user = userService.getById(id);
            MessageDTO messageDTO = new MessageDTO();
            BeanUtils.copyProperties(message, messageDTO);
            messageDTO.setRecipientInfo(user);
            messageDTOS.add(messageDTO);
        });

        return Result.success(messageDTOS);
    }

    @Override
    public Result<List<Messages>> receiveUnreadMessages(int receiverId) {
        List<Messages> messages = lambdaQuery().eq(Messages::getReceiverId, receiverId).eq(Messages::getStatus, 0).list();
        return Result.success(messages);
    }

    @Override
    public Result<List<Messages>> getMessagesBySenderIdAndReceiverId(int senderId, int receiverId) {
        List<Messages> messages = list(new LambdaQueryWrapper<Messages>()
                .eq(Messages::getSenderId, senderId)
                .eq(Messages::getReceiverId, receiverId)
                .or()
                .eq(Messages::getSenderId, receiverId)
                .eq(Messages::getReceiverId, senderId)
                .orderByAsc(Messages::getCreatedTime)
        );
        return Result.success(messages);
    }


    @Override
    public void markAsRead(int senderId) {
        LambdaUpdateWrapper<Messages> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Messages::getSenderId, senderId)
                .eq(Messages::getStatus, 0)
                .set(Messages::getStatus, 1);
        update(wrapper);
    }
}

